package internal

import (
	"BJXM_Shooting/common"
	"BJXM_Shooting/db/set"
	"BJXM_Shooting/game"
	"BJXM_Shooting/msg"
	"github.com/name5566/leaf/gate"
	"github.com/name5566/leaf/log"
	"reflect"
)

func handleMsg(m interface{}, h interface{}) {
	skeleton.RegisterChanRPC(reflect.TypeOf(m), h)
}

func init() {
	// 注册ChanRPC注册信息
	handleMsg(&msg.C2S_Register{}, handleRegister)
	handleMsg(&msg.C2S_Login{}, handleLogin)
}

func handleRegister(args []interface{}) {
	m := args[0].(*msg.C2S_Register)
	a := args[1].(gate.Agent)
	if m == nil {
		a.Close()
		return
	}

	log.Release("Address:%s 注册账号:%s", a.RemoteAddr().String(), m.Account)
	// 进行账号注册等
	err := set.Register(m.Account, m.Password, common.GetNickname(), common.GetAvatar())
	if err != nil { //注册失败
		a.WriteMsg(&msg.S2C_Register{
			ID:  msg.S2C_ID_RegisterFailed,
			Msg: err.Error(),
		})
		return
	} else { //注册成功
		a.WriteMsg(&msg.S2C_Register{
			ID:  msg.S2C_ID_RegisterSuccess,
			Msg: "注册成功",
		})
	}
}

func handleLogin(args []interface{}) {
	m := args[0].(*msg.C2S_Login)
	a := args[1].(gate.Agent)
	if m == nil {
		a.Close()
		return
	}
	log.Release("Address:%s 登录账号:%s", a.RemoteAddr().String(), m.Account)
	// 进行账号登录
	err := set.Login(m.Account, m.Password)
	if err != nil { //登录失败
		a.WriteMsg(&msg.S2C_Login{
			ID:  msg.S2C_ID_LoginFailed,
			Msg: err.Error(),
		})
		return
	}
	// 然后到Game模块中去操作别的
	game.ChanRPC.Go("UserLogin", a, m.Account)
	// 登录成功
	a.WriteMsg(&msg.S2C_Login{
		ID:  msg.S2C_ID_LoginSuccess,
		Msg: "登录成功",
	})
}
